package org.xmonkey.notifier.model;

import java.util.HashMap;

import org.eclipse.core.resources.IProject;

/**
 * This class represents all the subscriptions for project's end/start visits
 * @author jacopom
 *
 */
public class ProjectVisitSubscriptions extends HashMap<IProject, OrderedSubscribersList> {

	private static final long serialVersionUID = 3366913238350397157L;

	/**
	 * Subscribe for this project
	 * @param project the project
	 * @param subscriber the subscriber that will be notified
	 */
	public void subscribe(IProject project, ISubscriber subscriber) {
		if (!this.containsKey(project)){
			this.put(project, new OrderedSubscribersList());
		}
		this.get(project).add(subscriber);
	}

	/**
	 * Remove the subscription for this project
	 * @param project the project
	 * @param subscriber the subscriber to be removed
	 */
	public void removeSubscriptions(IProject project, ISubscriber subscriber) {
		if (this.containsKey(project)){
			this.get(project).removeSubscriptionsFor(subscriber);
		}
	}
	
	/**
	 * Notify the subscribers of the given project
	 * @param project the project
	 * @param start true if it must notfy a start-event, false if it must notify an end-event
	 */
	private void notify(IProject project, boolean start){
		if (this.containsKey(project)){
			// shallow copy to permit clients to modify the original one
			OrderedSubscribersList list = new OrderedSubscribersList(this.get(project));
			for(ISubscriber subscriber : list){
				if(start){
					subscriber.reactToStart(project);
				} else {
					subscriber.reactToEnd(project);
				}
			}
		}
	}

	/**
	 * Notify a start-event
	 * @param project the project
	 */
	public void notifyStart(IProject project) {
		notify(project, true);
	}

	/**
	 * Notify an end-event
	 * @param project the project
	 */
	public void notifyEnd(IProject project) {
		notify(project, false);
	}

}
